package com.hyg.common.utils;

import android.content.Context;
import android.provider.Settings;
import android.view.inputmethod.InputMethodManager;

/**
 * 修改默认输入法
 * 需要加上权限<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>
 * WRITE_SECURE_SETTINGS需要系统签名，同时要加上 android:sharedUserId="android.uid.system"
 * Author: HuangYuGuang
 * Date: 2023/4/1
 */
public class InputMethodUtil {
    /**
     * 若谷歌输入法已安装，则设其为系统默认输入法
     * (写入Android系统数据库)
     */
    public static void setDefaultInputMethod(Context context) {
        //获取系统已安装的输入法ID
        String[] methods = getInputMethodIdList(context);
        if (methods == null || methods.length == 0) {
            LogUtils.w(String.format("found no input method."));
            return;
        }

        //检查是否安装谷歌输入法
        //谷歌输入法ID "com.google.android.inputmethod.pinyin/.PinyinIME";
        String targetKeyword = "google";
        String value = "";
        for (String m : methods){
            LogUtils.d(String.format("find : %s", m));
            if (m.toLowerCase().contains(targetKeyword.toLowerCase())){
                value = m;//找到谷歌输入法
            }
        }
        if (value == "") {
            LogUtils.w(String.format("didn't find " + targetKeyword));
            return;
        }

        //设置默认输入法
        String key = Settings.Secure.DEFAULT_INPUT_METHOD;
        boolean success = Settings.Secure.putString(context.getContentResolver(), key, value);
        LogUtils.d(String.format("writeDbDefaultInputMethod(%s),result: %s", value,success));

        //读取默认输入法
        String current = Settings.Secure.getString(context.getContentResolver(),key);
        LogUtils.d(String.format("current default: %s",current));
    }

    /**
     * 获取系统已安装的输入法ID
     * @param context
     * @return
     */
    public static String[] getInputMethodIdList(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null && imm.getInputMethodList() != null) {
            String[] methodIds = new String[imm.getInputMethodList().size()];
            for (int i = 0; i <imm.getInputMethodList().size(); i++) {
                methodIds[i] = imm.getInputMethodList().get(i).getId();
                LogUtils.d("InputMethodId: " + methodIds[i]);
            }
            return methodIds;
        }
        return new String[]{};
    }
}